// pages/profile/settings.js
const app = getApp();

Page({
  data: {
    userInfo: {},
    settings: {
      notification: true,
      eventReminder: true
    },
    cacheSize: '0 KB'
  },

  onLoad() {
    this.loadUserInfo();
    this.loadSettings();
    this.calculateCacheSize();
  },

  /**
   * 加载用户信息
   */
  loadUserInfo() {
    this.setData({
      userInfo: app.globalData.userInfo || {}
    });
  },

  /**
   * 加载设置
   */
  loadSettings() {
    const settings = wx.getStorageSync('settings') || {
      notification: true,
      eventReminder: true
    };
    this.setData({ settings });
  },

  /**
   * 计算缓存大小
   */
  calculateCacheSize() {
    try {
      const { keys } = wx.getStorageInfoSync();
      let totalSize = 0;
      
      keys.forEach(key => {
        const data = wx.getStorageSync(key);
        totalSize += JSON.stringify(data).length;
      });

      const sizeInKB = (totalSize / 1024).toFixed(2);
      this.setData({
        cacheSize: sizeInKB > 1024 ? `${(sizeInKB / 1024).toFixed(2)} MB` : `${sizeInKB} KB`
      });
    } catch (e) {
      console.error('计算缓存大小失败:', e);
    }
  },

  /**
   * 编辑资料
   */
  editProfile() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  },

  /**
   * 选择城市
   */
  selectCity() {
    const cities = ['北京', '上海', '广州', '深圳', '杭州', '成都', '武汉', '西安'];
    
    wx.showActionSheet({
      itemList: cities,
      success: (res) => {
        const city = cities[res.tapIndex];
        const userInfo = this.data.userInfo;
        userInfo.city = city;
        
        this.setData({ userInfo });
        
        // TODO: 调用API更新用户信息
        wx.showToast({
          title: '城市已更新',
          icon: 'success'
        });
      }
    });
  },

  /**
   * 切换消息通知
   */
  toggleNotification(e) {
    const notification = e.detail.value;
    const settings = this.data.settings;
    settings.notification = notification;
    
    this.setData({ settings });
    wx.setStorageSync('settings', settings);
    
    wx.showToast({
      title: notification ? '已开启通知' : '已关闭通知',
      icon: 'none'
    });
  },

  /**
   * 切换活动提醒
   */
  toggleEventReminder(e) {
    const eventReminder = e.detail.value;
    const settings = this.data.settings;
    settings.eventReminder = eventReminder;
    
    this.setData({ settings });
    wx.setStorageSync('settings', settings);
    
    wx.showToast({
      title: eventReminder ? '已开启提醒' : '已关闭提醒',
      icon: 'none'
    });
  },

  /**
   * 清除缓存
   */
  clearCache() {
    wx.showModal({
      title: '确认清除',
      content: '确定要清除缓存吗？',
      success: (res) => {
        if (res.confirm) {
          wx.clearStorageSync();
          
          this.setData({ cacheSize: '0 KB' });
          
          wx.showToast({
            title: '缓存已清除',
            icon: 'success'
          });

          // 重新登录
          setTimeout(() => {
            app.logout();
          }, 1500);
        }
      }
    });
  },

  /**
   * 检查更新
   */
  checkUpdate() {
    if (wx.getUpdateManager) {
      const updateManager = wx.getUpdateManager();

      updateManager.onCheckForUpdate((res) => {
        if (res.hasUpdate) {
          wx.showToast({
            title: '发现新版本',
            icon: 'none'
          });

          updateManager.onUpdateReady(() => {
            wx.showModal({
              title: '更新提示',
              content: '新版本已准备好，是否重启应用？',
              success: (res) => {
                if (res.confirm) {
                  updateManager.applyUpdate();
                }
              }
            });
          });

          updateManager.onUpdateFailed(() => {
            wx.showToast({
              title: '更新失败',
              icon: 'none'
            });
          });
        } else {
          wx.showToast({
            title: '已是最新版本',
            icon: 'none'
          });
        }
      });
    } else {
      wx.showToast({
        title: '当前版本不支持',
        icon: 'none'
      });
    }
  },

  /**
   * 显示隐私政策
   */
  showPrivacy() {
    wx.showModal({
      title: '隐私政策',
      content: '我们重视您的隐私，详细隐私政策请访问官网查看。',
      showCancel: false
    });
  },

  /**
   * 显示用户协议
   */
  showTerms() {
    wx.showModal({
      title: '用户协议',
      content: '使用本服务即表示您同意我们的用户协议，详细协议请访问官网查看。',
      showCancel: false
    });
  },

  /**
   * 联系我们
   */
  contactUs() {
    wx.showModal({
      title: '联系我们',
      content: '客服邮箱：support@fun-sport.com\n客服电话：400-123-4567',
      showCancel: false
    });
  }
});

